package com.rrd.dw.mr.gzip.kafka;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ucredit.babel.common.model.BaseModel;
import com.ucredit.babel.common.model.RecordType;
import com.ucredit.babel.common.model.tianji.TianjiActionV2Data;
import com.ucredit.babel.common.model.tianji.TianjiActionV2Record;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper.Context;

import java.io.IOException;

/**
 * 天机行为接口V2
 *
 * @author renzhanzheng
 */

public class TianjiActionV2Parse extends ParseBase {
    private Text val = new Text();
    private Text key = new Text();

    /**
     *
     * 天机行为接口V2
     * @param model
     * @throws IOException
     * @throws InterruptedException
     * @return
     */
    @Override
    public boolean parseJob(Context context, BaseModel<?> model, String successful) throws IOException, InterruptedException {
        TianjiActionV2Record obj = (TianjiActionV2Record)model;
        TianjiActionV2Data data = obj.getData();
        JSONObject info = data.getData() == null ? new JSONObject() : JSON.parseObject(data.getData());
        JSONObject tianji = JSON.parseObject(info.getString("tianji_api_agentn_scorev20_response")) == null ? new JSONObject() : JSON.parseObject(info.getString("tianji_api_agentn_scorev20_response"));
        JSONObject tags = JSON.parseObject(tianji.getString("tags")) == null ? new JSONObject() : JSON.parseObject(tianji.getString("tags"));

        StringBuilder sb = getBaseInfo(obj, successful);

        //错误码
        sb.append(info.getString("error") == null ? "" : info.getString("error")).append(CRT001);
        //错误信息
        sb.append(info.getString("msg") == null ? "" : info.getString("msg")).append(CRT001);
        //request_id
        sb.append(info.getString("request_id") == null ? "" : info.getString("request_id")).append(CRT001);
        //唯一标识请求的UUID
        sb.append(tianji.getString("req_id") == null ? "" : tianji.getString("req_id")).append(CRT001);
        //业务流水号
        sb.append(tianji.getString("biz_id") == null ? "" : tianji.getString("biz_id")).append(CRT001);
        //综合风控评分
        sb.append(tags.getString("credit_score") == null ? "" : tags.getString("credit_score")).append(CRT001);

        key.set(getKey());
        val.set(sb.toString().replace("\n", " ").replace("\r", " "));
        context.write(key, val);

        return true;
    }

    @Override
    public String getTableName() {
        return "kafka_babel_tianji_actionv2_inc";
    }

    @Override
    public String getType() {
        return RecordType.TIANJI_ACTIONV2_RECORD.toString();
    }

    @Override
    public String getComment() {
        return "天机行为接口V2";
    }
}
